package scheduler

import (
	"01-crawler-project/03_distributed/engine"
)

type QueuedScheduler struct {
	requestCan chan engine.Request

	workerChan chan chan engine.Request
}

func (s *QueuedScheduler) WorkChan() chan engine.Request {

	return make(chan engine.Request)
}

func (s *QueuedScheduler) Submit(request engine.Request) {

	s.requestCan <- request

}

func (s *QueuedScheduler) WorkerReady(workerChan chan engine.Request) {

	s.workerChan <- workerChan

}

func (s *QueuedScheduler) SetWorkerChan(workerChan chan engine.Request) {

	//s.workerChan = workerChan

}
func (s *QueuedScheduler) Run() {

	s.workerChan = make(chan chan engine.Request)

	s.requestCan = make(chan engine.Request)

	go func() {

		var requestQ [] engine.Request

		var workerQ [] chan engine.Request

		for true {
			var activeRequest engine.Request

			var activeWorker chan engine.Request

			if len(requestQ) > 0 && len(workerQ) > 0 {

				activeRequest = requestQ[0]

				activeWorker = workerQ[0]
			}

			select {

			case r := <-s.requestCan:

				requestQ = append(requestQ, r)

			case w := <-s.workerChan:

				workerQ = append(workerQ, w)

			case activeWorker <- activeRequest:

				requestQ = requestQ[1:]

				workerQ = workerQ[1:]
			}

		}
	}()

}
